import styles from './index.module.css'
import React, { useEffect, useState } from 'react'
import { ImageUploader } from 'antd-mobile'
import imageCompression from 'browser-image-compression';

function ImagePick() {
    //已上传的文件列表
    const [fileList, setFileList] = useState([])

    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        //返回的函数相当于unmountComponentAtNode
        return () => {

        }
    }, []);


    function initData() {

    }

    function imageUploaderChange(items) {
        setFileList(items)
        console.log('hm1', items);
    }

    function imageUploaderDelete(item) {
        console.log('hm3', item);
    }

    async function mockUpload(file) {
        console.log('hm2', file);
        console.log(`原始大小 ${file.size / 1024 / 1024} MB`);
        //压缩
        const options = {
            maxSizeMB: 1,//最大大小
            maxWidthOrHeight: 1920,//最大宽高
            useWebWorker: true,//是否用webworker
        }
        const compressedFile = await imageCompression(file, options);
        console.log(`压缩后大小 ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
        //转base64
        const reader = new FileReader();
        reader.readAsDataURL(compressedFile);
        reader.onload = function (e) {
            // e.target.result 即为base64结果
            //console.log(e.target.result);
        };
        return {
            url: URL.createObjectURL(file),
        }
    }


    return (
        <div>
            <div className={styles.img_container}>
                <ImageUploader onDelete={imageUploaderDelete} value={fileList} onChange={imageUploaderChange} upload={mockUpload} accept={'image/jpeg,image/jpg,image/png'} maxCount={4} />
            </div>
        </div>
    )
}

export default ImagePick;
